package com.jiguang.property.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.facetoface.models.AlipayTradePrecreateResponse;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.jiguang.property.service.ApiPayService;
import com.jiguang.property.utils.ZfbPayUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.beans.IntrospectionException;
import java.net.URLEncoder;
import java.util.Random;

@Slf4j
@Service
public class ApiPayServiceImpl implements ApiPayService {

    @Override
    public String createDownLineTrading(String orderNo,Double price,String urge) throws Exception {
            String format = "json";

            AlipayClient alipayClient = new DefaultAlipayClient(ZfbPayUtils.GatewayUrl,ZfbPayUtils.AppId,ZfbPayUtils.PrivateKey,format,ZfbPayUtils.Charset,ZfbPayUtils.PublicKey,ZfbPayUtils.SignType);
            //PC网页支付使用AlipayTradePagePayRequest传参，下面调用的是pageExecute方法
            AlipayTradePagePayRequest precreateRequest = new AlipayTradePagePayRequest();
            if(StringUtils.isEmpty(urge)){
                precreateRequest.setReturnUrl(ZfbPayUtils.NotifyUrl);
            }else {
                precreateRequest.setReturnUrl(ZfbPayUtils.NotifyUrl+"?urge=1");
            }
            // 组装支付参数
            JSONObject json = new JSONObject();
            json.put("out_trade_no", orderNo); // 订单号
            json.put("total_amount", String.valueOf(price)); // 订单金额
            json.put("subject", "订单名称"); // 订单标题
            json.put("product_code", "FAST_INSTANT_TRADE_PAY"); // 支付方式：PC网页支付

            // 设置请求参数
            precreateRequest.setBizContent(json.toString());

            try {
                // 调用 SDK 生成支付表单
                return alipayClient.pageExecute(precreateRequest).getBody();
            } catch (AlipayApiException e) {
                e.printStackTrace();
                return "支付请求失败：" + e.getMessage();
            }

    }
}
